package number_16;

import java.util.Arrays;

public class Solution {
    public int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int best = 100000;

        for (int i = 0; i < nums.length; i++) {
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            int j = i + 1;
            int k = nums.length - 1;
            while (j < k) {
                int sum = nums[i] + nums[j] + nums[k];
                if (sum == target) {
                    return sum;
                }

                if (sum < target) {
                    if (Math.abs(sum - target) < Math.abs(best - target)) {
                        best = sum;
                    }
                    j++;
                } else {
                    if (Math.abs(sum - target) < Math.abs(best - target)) {
                        best = sum;
                    }
                    k--;
                }
            }
        }
        return best;
    }

    public static void main(String[] args) {
        new Solution().threeSumClosest(new int[]{-1,2,1,-4}, 1);
    }
}
